package cn.hackcloud.annotation.aop;

import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LogAspect {
	@Pointcut("execution(public Integer cn.hackcloud.annotation.aop.MathCalculator.*(..))")
	public void pointcut() {
	}

	@Pointcut("@annotation(cn.hackcloud.annotation.aop.Timer)")
	public void timer() {
	}

	@Before("pointcut()")
	public void logStart(JoinPoint joinPoint) {
		Object[] args = joinPoint.getArgs();
		System.out.println(joinPoint.getSignature().getName() + "运行，参数列表是:" + Arrays.asList(args));
	}

	@Around("timer()")
	public void test(ProceedingJoinPoint joinPoint) {
		Instant start = Instant.now();
		try {
			joinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		Instant end = Instant.now();
		long millis = Duration.between(start, end).toMillis();
		System.out.println("耗时:"+millis);
	}

	// 无论方法正常结束还是异常结束
	@After("pointcut()")
	public void logEnd(JoinPoint joinPoint) {
		System.out.println(joinPoint.getSignature().getName() + "结束...");
	}

	@AfterReturning(value = "pointcut()", returning = "result")
	public void logReturn(Object result) {
		System.out.println("除法正常返回结果是:{" + result + "}");
	}

	@AfterThrowing(value = "pointcut()", throwing = "e")
	public void logException(Exception e) {
		System.out.println("除法异常，异常信息:{" + e + "}");
	}
}
